package com.enqualcomm.kids.mvp.chat;


import android.media.MediaPlayer;

/**
 * Created by yinzhiqun on 2015/5/30.
 * 管理MediaPlayer
 */
public class PlayerManager extends AbstractPlayerManager implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    private MediaPlayer mMediaPlayer;
    private String mCurrentFilePath;

    public PlayerManager(){
        //在创建出对象时，初始化mediaplayer对象
        initMediaPlayer();
    }

    private void initMediaPlayer() {
        localRelease();//最好先释放上一个mediaPlayer对象
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
    }


    @Override
    protected void localRelease() {
        if (mMediaPlayer!=null){
            mMediaPlayer.setOnCompletionListener(null);
            mMediaPlayer.setOnErrorListener(null);
//            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public void start(String path) {
        mCurrentFilePath = path;
        mMediaPlayer.reset();

        try {
//            mMediaPlayer.setDataSource(new FileOutputStream(path).getFD());
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            notifyObservers(PlayerObserver.PLAYING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        if (mMediaPlayer!=null&&mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
        }
        notifyObservers(PlayerObserver.IDLE);
        mCurrentFilePath = null;
    }

    @Override
    public String getCurrentFilePath(){
        return mCurrentFilePath;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        //mediaPlayer 播放完成回调
        notifyObservers(PlayerObserver.IDLE);
        mCurrentFilePath = null;
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        //mediaPlayer 发生错误时回调
        notifyObservers(PlayerObserver.ERROR);
        mCurrentFilePath = null;
        return false;
    }



}
